﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GoodMan.Portal.WebLogic;
using GoodMan.Infrastructure.Entities.Enum;
using GoodMan.Portal.Web.Areas.WorkSpace.Models;
using GoodMan.Tool.Framework;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Portal.Biz;

namespace GoodMan.Portal.Web.Areas.WorkSpace.Controllers
{
    /// <summary>
    /// 超级财务人员
    /// </summary>
    [ErrorHandle]
    [Warp]
    [Auth(UserRole.FinancialOfficer)]
    public class FinancialOfficerController : Controller
    {
        //
        // GET: /WorkSpace/financialOfficer/

        public ActionResult Index()
        {
            return View();
        }

        #region 用户
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult UserInfoList(UserModel model, int page = 0)
        {
            if (model.SystemRole == -1)
                model.SystemRole = -3;
            ViewBag.UserList = UserBiz.GetAllUserByWhere(page, 10, model.SystemRole, model.FloorId, model.Gender, -1, model.Dormitory, model.NickName, model.RealName);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            ViewBag.SearchModel = model;
            return View();
        }

        private string userNameEnd = "@xiao-life.com";
        /// <summary>
        /// 用户新增
        /// </summary>
        /// <returns></returns>
        public ActionResult NewUser()
        {
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }
        [HttpPost]
        public ActionResult NewUser(UserModel model)
        {
            var user = new User()
            {
                Birthday = DateTime.Now,
                CollegeId = model.CollegeId,
                CreateDate = DateTime.Now,
                Gender = model.Gender == 1 ? Gender.Male : Gender.Female,
                IdCardNo = model.IdCardNo,
                RealName = model.RealName,
                IsActivate = true,
                IsRefuse = model.IsRefuse == 1 ? true : false,
                NickName = model.NickName,
                Password = model.Password,
                Phone = model.Phone,
                FloorId = model.FloorId,
                Dormitory = model.Dormitory,
                QQ = model.QQ,
                UserName = model.UserName.ToLower() + userNameEnd,
                Classes = model.Classes,
                Departments = model.Departments,
                SystemRole = Infrastructure.Entities.Enum.UserRole.Officer
            };
            if (UserBiz.Register(user,true) == null)
            {
                LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}注册失败。注册数据为：{1}",
                   user.UserName, user.ToJson()));
                ViewBag.Error = "添加财务人员信息失败！";
            } 
            ViewBag.Error = "";
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }

        /// <summary>
        /// 用户修改
        /// </summary>
        /// <returns></returns>
        public ActionResult ModifyUser(string u = "", int page = 0)
        {
            ViewBag.page = page;
            ViewBag.User = new User().Find(u);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }
        [HttpPost]
        public ActionResult ModifyUser(UserModel model, int page)
        {
            var user = new User().Find(model.UserName);

            if (user != null)
            {
                user.Gender = model.Gender == 1 ? Gender.Male : Gender.Female;
                user.IdCardNo = model.IdCardNo;
                user.RealName = model.RealName;
                user.IsRefuse = false;
                user.NickName = model.NickName;
                user.Phone = model.Phone;
                user.QQ = model.QQ;
                user.Dormitory = model.Dormitory;
                user.FloorId = model.FloorId;
                user.SystemRole = Infrastructure.Entities.Enum.UserRole.Officer;

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}注册失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改财务人员信息失败！";
                    return View();
                }
                ViewBag.Error = "";
            }
            return Redirect("/workspace/FinancialOfficer/userinfolist?page=" + page);
        }

        public bool UserNameOnly(string UserName)
        {
            return UserBiz.UserNotExists(UserName);
        }
        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UserInfo(string u, int page = 0)
        {
            ViewBag.page = page;
            ViewBag.User = new User().Find(u);
            return View();
        }

        public ActionResult ModifyStatu(string u, int page, int s)
        {
            var user = new User().Find(u);

            if (user != null)
            {
                user.IsRefuse = s == 1 ? true : false;

                if (user.PostModify() != null)
                {
                    return Redirect("/workspace/FinancialOfficer/userinfolist?page=" + page);
                }
            }
            return Redirect("/workspace/FinancialOfficer/userinfolist?page=" + page);
        }

        public ActionResult ModifyPassWord(string u, int page)
        {
            ViewBag.page = page;
            ViewBag.userName = u;
            return View();
        }
        [HttpPost]
        public ActionResult ModifyPassWord(string u, int page, string Confirm)
        {
            var user = new User().Find(u);

            if (user != null)
            {
                user.Password = AesAlgorithm.Encrypt(Confirm);

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}注册失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改财务人员密码失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return Redirect("/workspace/FinancialOfficer/userinfolist?page=" + page);
        }

        public ActionResult DelUser(string u, int page)
        {
            var user = new User().Find(u);

            if (user != null)
            {

                if (user.PostDelete() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}注册失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "删除管理员信息失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return Redirect("/workspace/FinancialOfficer/userinfolist?page=" + page);

        }
        #endregion

        #region 订单统计
        public ActionResult OrdersStatistics(int page = 0, string realName = "", string dtstart = "", string dtend = "", int status = -1)
        {
            int orderCount = 0;
            decimal totalPrice = 0.00m;
            var orderList = OrderBiz.OrderQuery(UserRole.FinancialOfficer, -1, realName, dtstart, dtend, status,false, page, 10, ref orderCount, ref totalPrice);
            ViewBag.OrderList = orderList;

            #region 回填数据
            ViewBag.realName = realName;
            ViewBag.dtstart = dtstart;
            ViewBag.dtend = dtend;
            ViewBag.status = status;
            ViewBag.orderCount = orderCount;
            ViewBag.totalPrice = totalPrice;
            #endregion
            return View();
        }

        public ActionResult OrderDetail(int id)
        {
            Order order = new Order().Find(id.ToString());
            List<OrderDetail> orderDetailList = new OrderDetail().FindAll(c => c.OrderId == id);
            string name = System.Web.HttpContext.Current.User.Identity.Name;
            var user = new User().Find(name);
            ViewBag.User = user;
            ViewBag.Order = order;
            ViewBag.OrderDetail = orderDetailList;
            ViewBag.OrderHistory = new OrderHistory().FindAll(c => c.OrderId == order.Id);
            return View();
        }
        #endregion

        #region 个人信息
        /// <summary>
        /// 个人信息首页
        /// </summary>
        /// <returns></returns>
        public ActionResult MyInfo()
        {
            string userName = HttpContext.User.Identity.Name;
            ViewBag.UserModel = new User().Find(userName);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }

        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MyInfo(UserModel model)
        {
            var user = new User().Find(model.UserName);

            if (user != null)
            {
                user.Gender = model.Gender == 1 ? Gender.Male : Gender.Female;
                user.IdCardNo = model.IdCardNo;
                user.RealName = model.RealName;
                user.NickName = model.NickName;
                user.Phone = model.Phone;
                user.QQ = model.QQ;
                user.Dormitory = model.Dormitory;
                user.FloorId = model.FloorId;

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}修改个人信息失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改信息失败！";
                    return View();
                }
                ViewBag.UserModel = user;
                ViewBag.Error = "";
            }
            ViewBag.UserModel = user;
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }
        public ActionResult Secret()
        {
            return View();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="Confirm"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Secret(string Confirm)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);

            if (user != null)
            {
                user.Password = AesAlgorithm.Encrypt(Confirm);

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}修改密码失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改密码失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return View();
        }
        #endregion

        #region 返佣报表
          public ActionResult UserRebateReport(string startYear, string startMonth, string endYear, string endMonth,int page=0,int College=1)
        { 
            int currentYear = DateTime.Now.Year;
            List<Object> objList = null;

            objList = new List<object>();
            objList.Add(new { value = 0, name = "请选择" });
            for (int i = 2013; i <= currentYear; i++)
            {

                List<object> subList = null;

                subList = new List<object>();
                subList.Add(new { value = 0, name = "请选择" });
                for (int j = 1; j < 13; j++)
                {
                    subList.Add(new { value = j.ToString().PadLeft(2, '0'), name = j.ToString().PadLeft(2, '0') });
                } 
                objList.Add(new { value = i.ToString(), name = i.ToString(), children = subList });

            }

            ViewBag.MonthList = objList.ToJson();
            var list = RebateReportBiz.GetRebateReport(startYear, startMonth, endYear, endMonth, page,20);
            
              ViewBag.data = list;
            

            DateTime date = DateTime.Now.AddMonths(-1);
            if (startYear == null || startYear == "")
            {
                startYear = date.Year.ToString();
            }
            if (startMonth == null || startMonth == "")
            {
                startMonth = date.Month.ToString().PadLeft(2, '0');
            }
            if (endYear == null || endYear == "")
            {
                endYear = date.Year.ToString();
            }
            if (endMonth == null || endMonth == "")
            {
                endMonth = date.Month.ToString().PadLeft(2, '0');
            }

            ViewBag.startYear = startYear;
            ViewBag.startMonth = startMonth;
            ViewBag.endYear = endYear;
            ViewBag.endMonth = endMonth;

            return View();
        }
        [HttpPost]
        public ActionResult SearchRebateReport(string startYear, string startMonth, string endYear, string endMonth,int College=1)
        {
            return Redirect("/WorkSpace/FinancialOfficer/UserRebateReport?startYear=" + startYear + "&startMonth=" + startMonth + "&endYear=" + endYear + "&endMonth=" + endMonth);
        }
        #endregion
    }
}
